package com.itheima.tlias84.controller;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.controller.po.InsertStuParam;
import com.itheima.tlias84.controller.po.SelectStuPageParam;
import com.itheima.tlias84.service.StuService;
import com.itheima.tlias84.service.dto.SelectStuDTO;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/students")
public class StuController {

    @Resource
    StuService stuService;

    @GetMapping
    public ResultUtil selectStuByPage(SelectStuPageParam param) {
        if (Objects.nonNull(param.getPage()) && Objects.nonNull(param.getPageSize())) {
            return stuService.selectStuByPage(param);
        } else {
            return ResultUtil.failure("参数错误");
        }
    }

    @GetMapping("/{id}")
    public ResultUtil selectStuById(@PathVariable Integer id) {
        SelectStuDTO stu = stuService.selectStuById(id);
        if (Objects.nonNull(stu)) {
            return ResultUtil.success(stu);
        } else {
            return ResultUtil.failure();
        }
    }

    @Log
    @DeleteMapping("/{ids}")
    public ResultUtil deleteStuById(@PathVariable List<Integer> ids) {
        int flag = stuService.deleteStuById(ids);
        if (flag > 0) {
            return ResultUtil.success("成功删除" + flag + "条数据");
        } else {
            return ResultUtil.failure("删除失败");
        }
    }

    @Log
    @PostMapping
    public ResultUtil insertStu(@RequestBody InsertStuParam param) {
        int flag = stuService.insertStu(param);
        if (flag == 1) {
            return ResultUtil.success();
        }else {
            return ResultUtil.failure();
        }
    }

    @Log
    @PutMapping
    public ResultUtil updateStu(@RequestBody InsertStuParam param) {
        if (param.getId() != null) {
            int flag = stuService.updateStu(param);
            if (flag == 1) {
                return ResultUtil.success();
            } else {
                return ResultUtil.failure();
            }
        } else {
            return ResultUtil.failure();
        }
    }

    @Log
    @PutMapping("/violation/{id}/{score}")
    public ResultUtil stuViolation(@PathVariable("id") Integer id, @PathVariable("score") Integer score) {
        int i = stuService.stuViolation(id, score);
        if (i == 1) {
            return ResultUtil.success("学生" + id + "扣" + score + "分");
        } else {
            return ResultUtil.failure();
        }
    }

}
